package com.ithanwen.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ithanwen.mapper.ClazzMapper;
import com.ithanwen.mapper.StudentMapper;
import com.ithanwen.pojo.Clazz;
import com.ithanwen.pojo.ClazzQueryParam;
import com.ithanwen.pojo.PageResult;
import com.ithanwen.pojo.Student;
import com.ithanwen.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

/**
 * Created By tony
 * <br/>Date: 2025/7/14 15:54
 * <br/>Description:
 */
@Service
public class ClazzServiceImpl implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Override
    public PageResult<Clazz> page(ClazzQueryParam clazzQueryParam) {
        PageHelper.startPage(clazzQueryParam.getPage(), clazzQueryParam.getPageSize());
        List<Clazz> clazzList = clazzMapper.search(clazzQueryParam.getName(), clazzQueryParam.getBegin(), clazzQueryParam.getEnd());

        // 遍历列表并设置 status
        for (Clazz clazz : clazzList) {
            if (clazz.getBeginDate().isAfter(LocalDate.now())){
                clazz.setStatus("未开班");
            } else if (clazz.getEndDate().isBefore(LocalDate.now())) {
                clazz.setStatus("已结束");
            } else {
                clazz.setStatus("已开班");
            }
        }
        PageResult<Clazz> pageResult = new PageResult<>(new PageInfo<>(clazzList).getTotal(), clazzList);
        return pageResult;
    }

    @Override
    public void deleteById(Integer id) {
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("clazz_id", id);
        if (studentMapper.selectCount(queryWrapper) > 0) {
            throw new RuntimeException("该班级下有学生，不能删除");
        }else {
            clazzMapper.deleteById(id);
        }
    }

    @Override
    public void add(Clazz clazz) {
        clazzMapper.insert(clazz);
    }

    @Override
    public Clazz findById(Integer id) {
        Clazz clazz = clazzMapper.selectById(id);
        return clazz;
    }

    @Override
    public List<Clazz> findall() {
        return clazzMapper.selectList(null);
    }

    @Override
    public void update(Clazz clazz) {
        QueryWrapper<Clazz> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", clazz.getId());
        if(clazzMapper.selectCount(queryWrapper) > 0){
            clazz.setUpdateTime(LocalDateTime.now());
            clazzMapper.updateById(clazz);
        }else{
            throw new RuntimeException("班级不存在");
        }
    }
}
